package com.hyfrogx.modules.app.controller;

import com.hyfrogx.common.param.Constants;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.config.wx.ConfigsWx;
import com.hyfrogx.modules.app.utils.WXPayUtil;
import com.hyfrogx.modules.manage.controller.BaseController;
import com.hyfrogx.modules.manage.entity.chargePayRecord.ChargePayRecordEntity;
import com.hyfrogx.modules.manage.service.chargePayRecord.ChargePayRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Map;

/**
 * Package: com.hyfrogx.modules.app.controller
 * Author: gyz
 * Date: Created in 2020/2/28 20:56
 * Company: 汉咏科技
 * Version: 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("callback")
public class CallBackController extends BaseController {
	@Autowired
	ChargePayRecordService chargePayRecordService;
	@Autowired
	ConfigsWx configsWx;


	/**
	 * 支付宝回调
	 *
	 * @param request
	 * @return
	 */
	@PostMapping(value = "status/alipay")
	public R callBackFromZhiFuBao(HttpServletRequest request, HttpServletResponse response) {
		try {
			System.out.println("ll");
			chargePayRecordService.notify(request,response);
			return R.ok();
		}catch (Exception e){
			return R.error(e.getMessage());
		}
	}

	/**
	 * 处理微信的回调
	 *
	 * @param request
	 * @return
	 */
	@PostMapping(value = "status/wx")
	public void callBackFromWeiXin(HttpServletRequest request,HttpServletResponse response) {
		try {
			// 获取支付宝POST过来反馈信息
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(request.getInputStream(), Constants.CharSet.utf8));
			log.info("获取反馈信息"+reader.toString());
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append("\r\n");
			}
			String data = sb.toString();
			log.info("data数据:"+data);
			Map<String, String> params = WXPayUtil.xmlToMap(data);
			log.info("XML格式字符串转换为Map:"+params.toString());
			try {
				if (params.get("return_code").equals(Constants.WeiXinStatus.SUCCESS)) {
					// 验证签名是否正确
					boolean status = WXPayUtil.isSignatureValid(params, configsWx.getApi_key());
					log.info("status:"+status);
					if (status) {
						// 业务结果成功
						if (params.get("result_code").equals(Constants.WeiXinStatus.SUCCESS)) {
							ChargePayRecordEntity chargePayRecord = new ChargePayRecordEntity();
							chargePayRecord.setOutTradeNo(params.get("out_trade_no"));
							chargePayRecord.setStatus(Constants.PayStatus.SUCCESS);
							chargePayRecord.setBuyerPayAmount(new BigDecimal(Float.valueOf(params.get("cash_fee"))/100));
							chargePayRecord.setReceiptAmount(new BigDecimal(Float.valueOf(params.get("total_fee"))/100));
							chargePayRecordService.upDateByOutTradeNo(chargePayRecord);
							log.info("chargePayRecord:"+chargePayRecord);
						} else {
							ChargePayRecordEntity chargePayRecord = new ChargePayRecordEntity();
							chargePayRecord.setOutTradeNo(params.get("out_trade_no"));
							chargePayRecord.setStatus(Constants.PayStatus.FAIL);
							chargePayRecord.setBuyerPayAmount(new BigDecimal(Float.valueOf(params.get("cash_fee"))/100));
							chargePayRecord.setReceiptAmount(new BigDecimal(Float.valueOf(params.get("total_fee"))/100));
							chargePayRecordService.upDateByOutTradeNo(chargePayRecord);
							log.info("chargePayRecord2:"+chargePayRecord);
						}
						response.getWriter().write("<xml>"
								+ "<return_code><![CDATA[SUCCESS]]></return_code>"
								+ "<return_msg><![CDATA[OK]]></return_msg>"
								+ "</xml>");
						log.info("response写入："+response.toString());
						return ;

					} else {
						log.error("订单签名验证失败" + params.get("out_trade_no"));
						return ;
					}
				} else {
					log.error(params.toString());
					return;
				}
			} catch (Exception e) {
				log.error("订单处理失败");
				return;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			return;
		}
	}
}
